<?php

Yii::import("application.components.evaluators.CompilerBase");

class ArchiveCompiler extends CompilerBase {

    private $target;
    private $tmpDir;

    public function __construct($request) {
        parent::__construct($request);
    }

    /**
     * Membersihkan berkas-berkas temporer dari disk 
     */
    protected function afterCompile() {
        
    }

    protected function beforeCompile() {
        $this->targetFilePath = $this->getGradingDirectory() . "/" . $this->requestModel->source_file;
        file_put_contents($this->targetFilePath , $this->requestModel->file);
    }

    /**
     * Membuat berkas script (.sh) yang dapat dipanggil untuk kemudian dieksekusi oleh grader
     */
    protected function generateExecutionScript() {
        if ($this->compileReturnValue == 0) {
            $this->executionScriptPath = $this->gradingDirectory . "/execute.sh";
            $executionCommand = "make grade OUTPUT=$this->gradingDirectory/Main -f $this->gradingDirectory/Makefile -C $this->gradingDirectory";
            file_put_contents($this->executionScriptPath, $executionCommand);
        } else {
            $this->executionScriptPath = "";
        }
    }

    /**
     * Mengeset target dari Makefile yang diinginkan
     * @param string $target 
     */
    public function setTarget($target) {
        $this->target = $target;
    }

    /**
     * Melakukan kompilasi, akan mengeset compileReturnValue dengan nilai kembalian proses kompilasi. 0 jika sukses, selain itu gagal.
     * Pesan kompilasi dapat diambil dari compileOutput
     * Program hasil kompilasi dapat diambil di outputFilePath
     * I.S: Direktori temporer sudah dibuat dengan Makefile di dalamnya. Jika tidak ada Makefile, return value != 0
     * F.S: compileOutput, compileReturnValue, outputFilePath terisi 
     */
    protected function doCompile() {
        $tmpDir = $this->gradingDirectory;

        ///Unzipping
        exec("unzip -o " . $this->targetFilePath . " -d $tmpDir");
        
        ///Injecting grader tester file
        //$testerFileName = $this->requestModel->evaluationset->getConfig("testerfilename");
        //file_put_contents($this->gradingDirectory . "/" . $testerFileName, $this->requestModel->evaluationset->file);

        ///Do compile process!
        //exec("make $this->target OUTPUT=$tmpDir/Main TESTER=$testerFileName -f $tmpDir/Makefile -C $tmpDir 2>&1", $out, $return);
        exec("make $this->target OUTPUT=$tmpDir/Main -f $tmpDir/Makefile -C $tmpDir 2>&1", $out, $return);
        
        $this->compileOutput = implode("\n", $out);
        $this->compileReturnValue = $return;

        if ($return == 0) {
            $this->outputFilePath = $tmpDir . "/Main";
        }
        else {
            $this->outputFilePath = "";
        }
    }

}

?>
